<template>
  <div class="app">
    <div class="search-bar">
      <el-form :model="searchData" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="角色名称" style="margin-bottom: 5px;">
              <el-input v-model="searchData.roleName" size="medium" class="input" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="角色状态" style="margin-bottom: 5px;">
              <el-input v-model="searchData.isValid" size="medium" class="input" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <div style="margin-top: 3px;">
              <el-button icon="el-icon-search" type="primary" size="small" @click="handleSearch">查询</el-button>
              <el-button icon="el-icon-refresh-left" size="small" @click="handleClear">重置</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div ref="ref2" class="table-box">
      <div class="btn-bar">
        <el-button icon="el-icon-plus" type="primary" size="small" @click="handleAdd">新增</el-button>
      </div>
      <tableComponent
        class="table"
        :height="height"
        :data="tableData || []"
        :columns="rolesTableColumns"
        @change="tablePage"
        :table-option="tableOption"
        :page-option="searchData.page"
        :total="total"
        :stripe="stripe"
      >
        <template scope="scope">
          <el-button @click="listPower(scope.scope.row)" type="text" size="mini">菜单权限</el-button>
          <el-button @click="delRow(scope.scope.row)" type="text" size="mini">{{scope.scope.row.isValid==='有效'?'禁用':'启用'}}</el-button>
        </template>
      </tableComponent>
    </div>
    <el-dialog title="新增角色" :visible.sync="dialogVisible" width="40%">
      <el-form ref="form" :model="addForm" label-width="80px" style="padding: 0 30px;" :rules="rules">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName" size="small" class="input"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc" size="small" class="input"  type="textarea" :rows="2"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit('form')">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 菜单配置弹窗 -->
    <el-dialog title="菜单权限" :visible.sync="dialogVisibleList" width="40%" :before-close="handleCancleMenuList">
      <div class="tree-box">
        <el-tree
          ref="tree"
          :data="listData"
          show-checkbox
          node-key="menuCode"
          :props="defaultProps"
          :default-expand-all="true"
          :expand-on-click-node="false"
          :check-on-click-node="false"
          :default-checked-keys="checkedKeys"
          @check-change="listCheckd">
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span>{{ node.label }}</span>
            <div style="margin-right: 30px">
              <el-checkbox v-if="data.leval != '1'" size="mini" true-label="1" false-label="0" v-model="data.resourceCode" @change="() => change(node, data)">操作</el-checkbox>
              <!-- <el-radio v-if="data.leval != '1'" v-model="data.resourceCode" label="1" @change="() => change(node, data)">操作</el-radio> -->
            </div>
            <!-- <span>
              <el-switch
                v-if="data.leval != '1'"
                @change="() => change(node, data)"
                v-model="data.resourceCode"
                style="display: block"
                active-value="1"
                inactive-value="0"
                active-text="操作"
                inactive-text="查看">
              </el-switch>
            </span> -->
          </span>
        </el-tree>
      </div>
      <span slot="footer">
        <el-button @click="handleCancleMenuList">取 消</el-button>
        <el-button type="primary" @click="handleChangePower">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import tableComponent from '@/components/Table/table'
import { rolesTableColumns } from './index.js'
import { queryRoleList, addRoles, updateRole, queryAllMenu, linkMenuAndRole } from '@/api/modules/systemManage.js'

export default {
  components: {
    tableComponent
  },
  data() {
    return {
      searchData: {
        page: {
          pageNum: 1,
          pageSize: 10
        }
      },
      height: null,
      rolesTableColumns,
      tableData: [],
      tableOption: {
        isShowOperate: true,
        operateWidth: '100px'
      },
      total: 0,
      stripe: true,
      // 新增dialog===============
      dialogVisible: false,
      addForm: {
        roleName: '',
        roleDesc: '',
      },
      rules: {
        roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
        roleDesc: [{ required: true, message: '请输入角色描述', trigger: 'blur' }],
      },
      // 菜单权限dialog=================
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      listData: [],
      dialogVisibleList: false,
      selectId: [],
      saveRoleId: '',
      checkedKeys: [], // 已选中的节点
      checkedMenuItem: []
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.height = this.$refs.ref2.offsetHeight - 110
    })
    window.onresize = () => {
      this.height = this.$refs.ref2.offsetHeight - 110
    }
    this.initData(this.searchData)
  },
  destroyed(){
    window.onresize = null
  },
  methods: {
    initData(params) {
      queryRoleList(params).then(res => {
        if (res.data.code === '0') {
          this.tableData = res.data.body.list
          this.total = res.data.body.total
        } else {
          return false
        }
      })
    },
    // 查询
    handleSearch() {
      this.initData(this.searchData)
    },
    // 分页
    tablePage(val) {
      this.searchData.page = val
      this.initData(this.searchData)
    },
    // 重置
    handleClear() {
      this.searchData.roleName = ''
      this.searchData.valid = ''
    },
    // 新增
    handleAdd(formName) {
      this.dialogVisible = true
    },
    // dialog=============================
    // 点击确定新增人员
    handleSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          addRoles(this.addForm).then(res => {
            if (res.data.code === '0') {
              this.resetForm('form')
              this.dialogVisible = false
              this.$message.success('新增成功')
              this.initData(this.searchData)
            } else {
              return false
            }
          })
        } else {
          return false
        }
      })
    },
    delRow(row) {
      console.log(row)
      this.$confirm('确认改变角色状态', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (row.isValid === '失效') {
          const data = {
            roleCode: row.roleCode,
            status: '1'
          }
          updateRole(data).then(res => {
            if (res.data.code === '0') {
              this.$message.success('修改成功')
              this.initData(this.searchData)
            } else {
              return false
            }
          })
        } else if (row.isValid === '有效') {
          const data = {
            roleCode: row.roleCode,
            status: '0'
          }
          updateRole(data).then(res => {
            if (res.data.code === '0') {
              this.$message.success('修改成功')
              this.initData(this.searchData)
            } else {
              return false
            }
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消修改'
        })
      })
    },
    // 菜单弹窗===========================
    listPower(row) {
      this.saveRoleId = row.roleCode
      const data = {
        roleCode: row.roleCode
      }
      queryAllMenu(data).then(res => {
        if (res.data.code === '200') {
          this.listData = res.data.data
          this.filterListNode(this.listData)
          this.filterJurisdictionList(this.listData)
          this.dialogVisibleList = true
        }
      })
    },
    // 处理已经分配菜单的显示
    filterListNode(params) {
      for ( let item of params ) {
        if (item.realCode !== null) {
          this.checkedKeys.push(item.realCode)
          // console.log(this.checkedKeys)
          this.selectId = this.checkedKeys
        }
        if (item.children !== null) {
          this.filterListNode(item.children)
          item.leval = '1'
        }
      }
    },
    // 处理已分配权限的菜单
    filterJurisdictionList(params) {
      for (let item of params) {
        if (item.resourceCode === '1') {
          this.checkedMenuItem.push(item)
        }
        if (item.children != null) {
          this.filterJurisdictionList(item.children)
        }
      }
    },
    listCheckd(val) {
      this.selectId = this.$refs.tree.getCheckedKeys().concat(this.$refs.tree.getHalfCheckedKeys())
    },
    change(node, data) {
      console.log(node,data)
      this.checkedMenuItem.push(data)
      if (node.checked === false) {
        this.$message.error('请先分配菜单')
        data.resourceCode = '0'
      }
    },
    // 点击确定分配权限
    handleChangePower() {
      let arr = this.checkedMenuItem.filter(item => {
        return item.resourceCode != '0'
      })
      // console.log(arr)
      const obj = {
        roleCode: this.saveRoleId,
        menuCode: this.selectId,
        listData: arr
      }
      linkMenuAndRole(obj).then(res => {
        if (res.data.code === '200') {
          this.$message.success('修改成功')
          this.dialogVisibleList = false
          this.checkedKeys = []
          this.checkedMenuItem = []
        }
      })
    },
    handleCancleMenuList() {
      this.checkedKeys = []
      this.checkedMenuItem = []
      this.dialogVisibleList = false
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style lang="less" scoped>
  .app {
    .search-bar {
      width: calc(100% - 60px);
      margin-bottom: 10px;
      padding: 0 30px;
      .input {
        width: 100%;
      }
    }
    .table-box {
      width: 100%;
      height: calc(100vh - 190px);
      .btn-bar {
        padding: 10px 0;
      }
      .table {
        height: 100%;
      }
    }
    .input {
      width: 100%;
    }
    .tree-box {
      height: 50vh;
      overflow: auto;
      .custom-tree-node {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 14px;
        padding-right: 8px;
      }
    }
  }
</style>